package com.example.musicplayer.util

import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.util.Log
import com.example.musicplayer.model.SongCategory

class CategoryDatabaseHelper(context: Context) :
    SQLiteOpenHelper(context, CATEGORY_DATABASE_NAME, null, DATABASE_VERSION) {

    companion object {
        internal const val CATEGORY_DATABASE_NAME = "song_category.db"
        const val DATABASE_VERSION = 3 // 增加版本号

        const val TABLE_SONG_CATEGORY = "song_category"
        const val COLUMN_CATEGORY_ID = "id"
        const val COLUMN_CATEGORY_NAME = "name"

        private const val CREATE_TABLE_SONG_CATEGORY = """
            CREATE TABLE $TABLE_SONG_CATEGORY (
                $COLUMN_CATEGORY_ID INTEGER PRIMARY KEY AUTOINCREMENT,
                $COLUMN_CATEGORY_NAME TEXT NOT NULL
            )
        """
    }

    override fun onCreate(db: SQLiteDatabase) {
        db.execSQL(CREATE_TABLE_SONG_CATEGORY)
        Log.d("CategoryDatabaseHelper", "Table created: $CREATE_TABLE_SONG_CATEGORY")
        initializeData(db)
    }

    override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
        if (oldVersion < 3) {
            // 删除旧表
            db.execSQL("DROP TABLE IF EXISTS $TABLE_SONG_CATEGORY")
            Log.d("CategoryDatabaseHelper", "Table dropped: $TABLE_SONG_CATEGORY")
            // 重新创建表
            onCreate(db)
        }
    }

    private fun initializeData(db: SQLiteDatabase) {
        val categories = listOf(
            SongCategory(name = "纯音乐"),
            SongCategory(name = "欧美"),
            SongCategory(name = "深夜EMO"),
        )

        for (category in categories) {
            val values = ContentValues().apply {
                put(COLUMN_CATEGORY_NAME, category.name)
            }
            db.insert(TABLE_SONG_CATEGORY, null, values)
            Log.d("CategoryDatabaseHelper", "Inserted category: ${category.name}")
        }
    }
}